@extends('backend.layout')
@section('style')
    <link href="/backend/css/plugins/bootstrap-table/bootstrap-table.css" rel="stylesheet">
    <link href="/backend/css/plugins/bootstrapValidator/bootstrapValidator.min.css" rel="stylesheet">

@endsection
@section('content')
    @include('backend.elements.breadcrumbs')

    <div class="wrapper wrapper-content animated fadeInRight">
        <div class="row">
            <div class="col-lg-12">
                <div class="ibox float-e-margins">
                    <div class="ibox-content">

                        <div class="table-responsive">
                            <div id="toolbar">
                                <button class="btn btn-primary"
                                        id="add">
                                    添加
                                </button>
                                <form action="/admin/photo/types/delete" method="post" style="display: inline">
                                    {{ csrf_field() }}
                                    <input type="hidden" id="batch-delete" name="batch-delete">
                                    <input type="submit" id="remove" class="btn btn-danger" value="删除" disabled>
                                </form>
                            </div>

                            <table id="table"
                                   data-toolbar="#toolbar"
                                   data-search="true"
                                   data-locale="en"
                                   data-show-refresh="true"
                                   data-show-toggle="true"
                                   data-show-columns="true"
                                   data-show-export="true"
                                   data-minimum-count-columns="2"
                                   data-show-pagination-switch="true"
                                   data-pagination="true"
                                   data-id-field="id"
                                   data-page-list="[5, 10, 20, 50, ALL]"
                                   data-show-footer="false"
                                   data-side-pagination="server"
                                   data-url="/api/photo/types"
                                   data-ajax-options="ajaxOptions"
                                   data-response-handler="responseHandler">
                            </table>
                        </div>

                    </div>
                </div>
            </div>
        </div>
    </div>
    @include('backend.types.form')
@endsection
@section('script')
    <script src="/backend/js/plugins/bootstrapValidator/bootstrapValidator.min.js"></script>
    <script src="/backend/js/plugins/bootbox/bootbox.min.js"></script>
    <script>
        window.ajaxOptions = {headers: { "Authorization": "Bearer {{ auth()->user()->api_token }}"}};
    </script>
    <script>
        var put_field = '<input type="hidden" name="_method" value="PUT">';
        var $table = $('#table'),
                $remove = $('#remove'),
                selections = [];

        function initTable() {
            $table.bootstrapTable({
                height: getHeight(),
                columns: [
                    [
                        {
                            field: 'state',
                            checkbox: true,
                            align: 'center',
                            valign: 'middle'
                        },
                        {
                            title: 'ID',
                            field: 'id',
                            align: 'center',
                            valign: 'middle',
                            sortable: true,
                        },
                        {
                            field: 'name',
                            title: '名字',
                            sortable: true,
                            align: 'center'
                        },
                        {
                            field: 'operate',
                            title: '操作',
                            align: 'center',
                            events: operateEvents,
                            formatter: operateFormatter
                        }
                    ]
                ]
            });
            // sometimes footer render error.
            setTimeout(function () {
                $table.bootstrapTable('resetView');
            }, 200);
            $table.on('check.bs.table uncheck.bs.table ' +
                    'check-all.bs.table uncheck-all.bs.table', function () {
                $remove.prop('disabled', !$table.bootstrapTable('getSelections').length);

                // save your data, here just save the current page
                selections = getIdSelections();
                // push or splice the selections if you want to save all data selections
            });
            $table.on('expand-row.bs.table', function (e, index, row, $detail) {
                if (index % 2 == 1) {
                    $detail.html('Loading from ajax request...');
                    $.get('LICENSE', function (res) {
                        $detail.html(res.replace(/\n/g, '<br>'));
                    });
                }
            });
            $table.on('all.bs.table', function (e, name, args) {
                console.log(name, args);
            });
            $remove.click(function (e) {
                e.preventDefault();
                var ids = getIdSelections();
                var $form= $(this).closest('form');
                bootbox.confirm({
                    message: "Delete Confirmation",
                    buttons: {
                        confirm: {
                            label: 'Yes',
                            className: 'btn-success'
                        },
                        cancel: {
                            label: 'No',
                            className: 'btn-danger'
                        }
                    },
                    callback: function (result) {
                        if(result) {
                            $('#batch-delete').val(ids.toString());
                            $form.submit();
                        }
                    }
                });
            });
            $(window).resize(function () {
                $table.bootstrapTable('resetView', {
                    height: getHeight()
                });
            });
        }

        function getIdSelections() {
            return $.map($table.bootstrapTable('getSelections'), function (row) {
                return row.id
            });
        }

        function responseHandler(res) {
            let data = {};
            data.rows = res.data.data;
            data.total = res.data.total;
            console.log('res',data);
            $.each(data.rows, function (i, row) {
                row.state = $.inArray(row.id, selections) !== -1;
            });
            return data;
        }

        function detailFormatter(index, row) {
            var html = [];
            $.each(row, function (key, value) {
                html.push('<p><b>' + key + ':</b> ' + value + '</p>');
            });
            return html.join('');
        }

        function operateFormatter(value, row, index) {
            return [
                '<a href="/admin/photo/upload?id=' + row.id + '" class="btn btn-success btn-sm">上传照片</a> ',
                '<a class="like" href="javascript:void(0)" title="Like">',
                '<button class="btn btn-primary btn-sm">编辑</button>',
                '</a>  ',
                '<form action="/admin/photo/types/' + row.id + '" method="POST" style="display: inline">',
                '{{ csrf_field() }}',
                '{{ method_field('DELETE') }}',
                '<input type="submit" class="remove btn btn-danger btn-sm" value="删除">',
                '</form>'
            ].join('');
        }

        window.operateEvents = {
            'click .like': function (e, value, row, index) {
                $('#name').val(row.name);
                $('#display-name').val(row.display_name);
                $('#validate-form').attr('action','/admin/photo/types/' + row.id);
                $('#validate-form').append(put_field);
                $('#modal-form').modal();
            },
            'click .remove': function (e, value, row, index) {
                e.preventDefault();
                var $form= $(this).closest('form');
                bootbox.confirm({
                    message: "确定删除?",
                    buttons: {
                        confirm: {
                            label: '是',
                            className: 'btn-success'
                        },
                        cancel: {
                            label: '否',
                            className: 'btn-danger'
                        }
                    },
                    callback: function (result) {
                        if(result) {
                            $form.submit();
                        }
                    }
                });

            }
        };


        function getHeight() {
            return $(window).height() - $('h1').outerHeight(true);
        }

        $(function () {
            var scripts = [
                        location.search.substring(1) || '/backend/js/plugins/bootstrap-table/bootstrap-table.js',
                        '/backend/js/plugins/bootstrap-table/bootstrap-table-export.js',
                        '/backend/js/plugins/bootstrap-table/locale/bootstrap-table-zh-CN.js'
                    ],
                    eachSeries = function (arr, iterator, callback) {
                        callback = callback || function () {};
                        if (!arr.length) {
                            return callback();
                        }
                        var completed = 0;
                        var iterate = function () {
                            iterator(arr[completed], function (err) {
                                if (err) {
                                    callback(err);
                                    callback = function () {};
                                }
                                else {
                                    completed += 1;
                                    if (completed >= arr.length) {
                                        callback(null);
                                    }
                                    else {
                                        iterate();
                                    }
                                }
                            });
                        };
                        iterate();
                    };
            eachSeries(scripts, getScript, initTable);
        });
        function getScript(url, callback) {
            var head = document.getElementsByTagName('head')[0];
            var script = document.createElement('script');
            script.src = url;
            var done = false;
            // Attach handlers for all browsers
            script.onload = script.onreadystatechange = function() {
                if (!done && (!this.readyState ||
                        this.readyState == 'loaded' || this.readyState == 'complete')) {
                    done = true;
                    if (callback)
                        callback();
                    // Handle memory leak in IE
                    script.onload = script.onreadystatechange = null;
                }
            };
            head.appendChild(script);
            // We handle everything using the script element injection
            return undefined;
        }
    </script>
    <script>
        $('#modal-form').on('hidden.bs.modal', function (e) {
            $('#validate-form').get(0).reset();
            $('#validate-form').data('bootstrapValidator').resetForm();
        });

        $('#validate-form').bootstrapValidator({
            feedbackIcons: {
                valid: 'glyphicon glyphicon-ok',
                invalid: 'glyphicon glyphicon-remove',
                validating: 'glyphicon glyphicon-refresh'
            },
            excluded: ':disabled',
            live: 'enabled',
            submitButtons: 'button[type="submit"]',
            fields: {
                name: {
                    validators: {
                        notEmpty: {
                            message: '权限名字不能为空'
                        }
                    }
                },
            }
        });

        $('#add').click(function () {
            $('#_method').remove();
            $('#validate-form').attr('action','/admin/photo/types');
            $('#modal-form').modal();
        });

    </script>
@endsection